import hashlib
from DBUtility import DBManage
import re


class Verification:
    def __init__(self):
        self.db = DBManage()

    def hash_password(self, password):
        """对密码进行hash加密"""
        return hashlib.md5(password.encode()).hexdigest()

    def get_unique(self, phone):
        """唯一性元素认证"""
        condition = f"phone = '{phone}'"
        result = self.db.select_data('tb_user', condition)
        return True if result else False  # 唯一元素认证成功或失败！

    def login_verify(self, table, account, password):
        """登录校验！用于管理端和用户端进行进行校验
        :param table:要操作的表
        :param account:账号或手机号
        :param password:密码
        """
        if table == 'tb_admin':
            condition = f"account = '{account}' AND password = '{password}'"
            result = self.db.select_data('tb_admin', condition)
        else:
            pwd = self.hash_password(password)  # 如果是用户登录！对输入的密码进行加密
            # 条件
            condition = f"phone = '{account}' AND password = '{pwd}' AND state='1'"
            result = self.db.select_data('tb_user', condition)
        if not result:
            raise Exception("账号或密码错误")  # 友好提示
        return True  # 校验通过

    def register_verify(self, phone, password):
        """注册校验"""
        ret = re.match(r"^1[35678]\d{9}$", phone)  # 正则表达式用于手机号校验
        if ret:
            # 获取唯一性元素--手机号
            if self.get_unique(phone):
                raise Exception("该手机号已被注册")  # 友好提示
            elif len(password) > 17 or len(password) < 5:
                raise Exception("密码格式不正确(密码由6~16个字符组成)")
            else:
                return True  # 登录校验通过
        else:
            raise Exception("手机号格式不正确！")  # 友好提示

    def enter_validation(self, *args):
        """验证输入数据是否为空！"""
        for arg in args:
            if arg is None or (isinstance(arg, str) and not arg.strip()):
                raise Exception("输入数据不能为空！")  # 友好提示
        return True  # 验证通过
